package com.shuhua.taskServer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shuhua.common.exception.BusinessException;
import com.shuhua.pojo.dto.AdminProfileUpdateDTO;
import com.shuhua.pojo.entity.Admin;
import com.shuhua.pojo.vo.AdminProfileVO;
import com.shuhua.pojo.vo.UserInfo;
import com.shuhua.taskServer.mapper.AdminMapper;
import com.shuhua.taskServer.service.AdminService;
import com.shuhua.taskServer.service.security.GenericUserDetails;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    /**
     * 从安全上下文中获取当前登录管理员的ID
     */
    private Long getCurrentAdminId() {
        try {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            GenericUserDetails<?> userDetails = (GenericUserDetails<?>) principal;
            UserInfo userInfo = userDetails.getUser();
            return userInfo.getId();
        } catch (Exception e) {
            throw new BusinessException(401, "用户未登录或认证信息无效");
        }
    }

    @Override
    public AdminProfileVO getAdminProfile() {
        Long adminId = getCurrentAdminId();
        Admin admin = adminMapper.selectById(adminId);
        if (admin == null) {
            throw new BusinessException(404, "管理员不存在");
        }
        AdminProfileVO vo = new AdminProfileVO();
        BeanUtils.copyProperties(admin, vo);
        return vo;
    }

    @Override
    public void updateAdminProfile(AdminProfileUpdateDTO dto) {
        Long adminId = getCurrentAdminId();
        // 检查手机号是否被其他管理员占用
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getPhone, dto.getPhone()).ne(Admin::getId, adminId);
        if (adminMapper.exists(queryWrapper)) {
            throw new BusinessException(409, "手机号已被占用");
        }

        Admin admin = adminMapper.selectById(adminId);
        if (admin == null) {
            throw new BusinessException(404, "管理员不存在");
        }

        // 手动赋值，更安全
        admin.setRealName(dto.getRealName());
        admin.setPhone(dto.getPhone());
        admin.setEmail(dto.getEmail());
        admin.setAvatar(dto.getAvatar());

        adminMapper.updateById(admin);
    }
}